package com.example.administrator.hqq.fragment.discover;


import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.administrator.hqq.R;
import com.example.administrator.hqq.View.GridViewInvalidListener;
import com.example.administrator.hqq.View.alertview.MyDialog;
import com.example.administrator.hqq.adapter.SetOnClickItem;
import com.example.administrator.hqq.adapter.discover.ConvenGridAdapter;
import com.example.administrator.hqq.base.MyFragemnt;
import com.example.administrator.hqq.bean.ConventionListBean;
import com.example.administrator.hqq.bean.MainActivityEventData;
import com.example.administrator.hqq.config.LoongsConfig;
import com.example.administrator.hqq.config.UrlFactory;
import com.example.administrator.hqq.fragment.MineFragment;
import com.google.gson.Gson;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Call;


/**
 * A simple {@link Fragment} subclass.
 * 常规模块页面
 */
public class ConventionFragment extends MyFragemnt {

    private final String TAG = this.getClass().getSimpleName();
    @BindView(R.id.conention_modie)
    GridViewInvalidListener conentionModie;
    @BindView(R.id.search_al)
    AutoRelativeLayout searchAl;
    Unbinder unbinder;
    private boolean aBoolean = false;
    private List<ConventionListBean.DataBean> data;
    private ConvenGridAdapter convenGridAdapter;
    private MyDialog myMiddleDialog;
    private View conventionViewPager;
    private List moduleData;
    private String topic_id;
    private @SuppressLint("WrongViewCast")
    AutoLinearLayout conventionLinear;
    private MineFragment.AddModule addModule;

    public void setAddModule(MineFragment.AddModule addModule) {
        this.addModule = addModule;
    }
    public ConventionFragment() {
        // Required empty public constructor
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_convention, container, false);

        unbinder = ButterKnife.bind(this, view);
        conentionModie.setOnTouchInvalidPositionListener(new GridViewInvalidListener.OnTouchInvalidPositionListener() {
            @Override
            public boolean onTouchInvalidPosition(int motionEvent) {
                if (aBoolean ) {
                    aBoolean = false;
                    convenGridAdapter.setaBoolean(aBoolean);
                    convenGridAdapter = new ConvenGridAdapter(getActivity(), data, aBoolean);
                    conentionModie.setAdapter(convenGridAdapter);
                    setDeleteTopicClick();
                }
                return false;
            }
        });
        EventBus.getDefault().register(this);
        initview();
        initdata();
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        convenGridAdapter.notifyDataSetChanged();
    }

    private void initdata() {
        //获取FirstData
        getFirstModuleData();
        getChildModuleData();
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initview() {
        data = new ArrayList<>();
        moduleData = new ArrayList();
        initConentionModile();
    }

    /**
     * 初始h化gridview和adapter
     */
    private void initConentionModile() {
        convenGridAdapter = new ConvenGridAdapter(getActivity(), data, aBoolean);
        conentionModie.setAdapter(convenGridAdapter);
        conentionModie.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (aBoolean ) {
                    aBoolean = false;
                    convenGridAdapter.setaBoolean(aBoolean);
                } else {
                    if (i==data.size()){
                        if (addModule!=null){
                            addModule.addModule("");
                        }
                    }
                    else{
                        Log.e(TAG, "点击位置onItemClick: "+i+data.get(i).getId());
                        //向主页发送Eventbus来更新群列表和贴纸fragment
                        MainActivityEventData mainActivityEventData = new MainActivityEventData(data.get(i).getId(), 4);
                        mainActivityEventData.setTopic_name(data.get(i).getName());
                        EventBus.getDefault().post(mainActivityEventData);
                        //更改位置顺序
                        OkHttpUtils.get().url(UrlFactory.getRefreshSequence())
                                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                                .addParams(LoongsConfig.topic_id,data.get(i).getId())
                                .build().execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                Log.e(TAG, "更新用户话题顺序onError: "+e.getMessage() );
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                Log.e(TAG, "更新用户话题顺序onResponse: "+response );
                                initdata();
                            }
                        });
//                        swap1(data,i,0);
                    }
                }
                convenGridAdapter = new ConvenGridAdapter(getActivity(), data, aBoolean);
                conentionModie.setAdapter(convenGridAdapter);
                setDeleteTopicClick();
            }
        });
        conentionModie.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                aBoolean = true;
                convenGridAdapter.setaBoolean(true);
                convenGridAdapter.notifyDataSetChanged();
                return true;
            }
        });
        setDeleteTopicClick();
    }

    private void setDeleteTopicClick() {
        convenGridAdapter.setSetOnClickItem(new SetOnClickItem() {
            @Override
            public void setOnClickItem(int position) {
                if (data.size()<=1)
                {
                    ToastUtils.showShort("不可删除最后一个话题");
                    return;
                }
                OkHttpUtils.get().url(UrlFactory.getUsertopicDeleteUserTopic())
                        .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                        .addParams(LoongsConfig.topic_id, data.get(position).getId())
                        .build().execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e(TAG, "删除用户话题: ");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e(TAG, "删除用户话题: ");
                    }
                });
                data.remove(position);
                convenGridAdapter.notifyDataSetChanged();
            }

            @Override
            public void setPicsOnClickItem(int position) {

            }
        });
    }

    /**
     * 创建展示子级module的dialog
     */
    @SuppressLint("WrongViewCast")
    private void creatDialog() {
        //设置自定义view
        myMiddleDialog = new MyDialog(getActivity(), R.style.MyMiddleDialogStyle);
        View DialogInflate = getLayoutInflater().inflate(R.layout.connention_dialog_item, null);
        conventionViewPager = DialogInflate.findViewById(R.id.convention_viewpager);
        conventionLinear = DialogInflate.findViewById(R.id.convention_linear);
        myMiddleDialog.setContentView(DialogInflate);
        Window window = myMiddleDialog.getWindow();
        //设置边框距离
        window.getDecorView().setPadding(0, 0, 0, 0);
        //设置dialog位置
        window.setGravity(Gravity.CENTER);
        //设置宽高
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //设置点击Dialog外部任意区域关闭Dialog
        window.setAttributes(lp);
        myMiddleDialog.setCanceledOnTouchOutside(true);
    }
    public static <T> void swap1(List<T> list, int oldPosition, int newPosition) {
        if (null == list) {
            throw new IllegalStateException("The list can not be empty...");
        }
        T tempElement = list.get(oldPosition);
        // 向前移动，前面的元素需要向后移动
        if (oldPosition < newPosition) {
            for (int i = oldPosition; i < newPosition; i++) {
                list.set(i, list.get(i + 1));
            }
            list.set(newPosition, tempElement);
        } // 向后移动，后面的元素需要向前移动
        if (oldPosition > newPosition) {
            for (int i = oldPosition; i > newPosition; i--) {
                list.set(i, list.get(i - 1));
            }
            list.set(newPosition, tempElement);
        }
    }

    /**
     * 获取一级模块数据
     */
    public void getFirstModuleData() {
        OkHttpUtils.get().url(UrlFactory.getUserFolder())
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "onError: " + e);
            }

            @Override
            public void onResponse(String s, int id) {
                Log.e(TAG, "onResponse: " + s);
                Gson gson = new Gson();
                ConventionListBean conventionListBean = gson.fromJson(s, ConventionListBean.class);
                if (conventionListBean.getCode() == 200) {
                    data.clear();
                    data.addAll(conventionListBean.getData());
                    convenGridAdapter.notifyDataSetChanged();
                    if (data!=null&&data.size()>0)
                    {

                    }
                } else if (conventionListBean.getCode() == 300) {
                    Log.e(TAG, "onResponse: ");
                }
            }
        });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(String string) {
        if ("更新常规模块".equals(string))
        {
            initdata();
        }
    }

    public List<ConventionListBean.DataBean> getData() {
        return data;
    }

    /**
     * 获取子级数据
     */
    public void getChildModuleData() {

    }
}